#coding: utf-8

import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import time
import pymongo
import redis
from topapi import *
from exceptions import Exception


def oid_iid_m2r(mdb, rdb):
    cur = mdb.trades.find(timeout=False, fields=['orders.order.oid', 'orders.order.num_iid', 'created'])
    cur.batch_size(100)
    for t in cur:
        order = t['orders']['order']
        created = t['created'].split(' ')[0]
        for o in order:
            oid = o['oid']
            iid = o['num_iid']
            key = '%d:%s' %(iid, created)
            if not rdb.sismember(key, oid):
                rdb.sadd(key, oid)
            rate = mdb.traderate.find_one({'_id':oid}, fields=['result', 'created'])
            if not rate:
                continue
            #rate:iid:day:result
            rate_created = rate['created'].split(' ')[0]
            key = 'rate:%d:%s:%s' %(iid, rate_created, rate['result'])
            if not rdb.sismember(key, oid):
                rdb.sadd(key, oid)




def start():
    m = pymongo.Connection('127.0.0.1:57324')
    mdb = m.taogold
    rdb = redis.Redis(host='127.0.0.1', port=56379, db=0)
    oid_iid_m2r(mdb, rdb)


if __name__ == '__main__':
    start()

